import axios from 'axios'
import type { AxiosInstance } from 'axios'

// 解决 类型“AxiosResponse＜any, any＞”上不存在属性问题
declare module "axios" {
    interface AxiosResponse<T = any> {
        code: 0;
    }
    export function create(config?: AxiosRequestConfig): AxiosInstance;
}

let newAxios: AxiosInstance
// 创建一个新的axios对象，用来请求token
if (process.env.NODE_ENV === 'production') {
    newAxios = axios.create({ baseURL: 'http://127.0.0.1:8000/v1' })
} else {
    newAxios = axios.create({ baseURL: '/v1' })
}

// 配置全局基础URL地址
if (process.env.NODE_ENV === 'production') {
    axios.defaults.baseURL = 'http://127.0.0.1:8000/v1'
} else {
    axios.defaults.baseURL = '/v1'
}
// 配置全局的请求超时时间
axios.defaults.timeout = 3000
// 请求token账号
const username: string = 'jack'
const password: string = '123'

// 配置axios请求拦截，将token设置到请求头部中
axios.interceptors.request.use(async config => {
    // localstorage中获取token，判断token是否存在并且是否过期
    let token: string | null = localStorage.getItem('token')
    if (!token || Date.now() > Number(localStorage.getItem('expires')) * 1000) {
        const { data: { code, data } } = await newAxios.post('/accesstoken', { username, password })
        if (code === 0) {
            localStorage.setItem('token', data.token)
            localStorage.setItem('expires', data.expires)
            token = data.token
        }
    }
    config.headers = {
        Authorization: `Bearer ${token}`
    }
    return config
})

// 响应拦截
axios.interceptors.response.use(response => {
    return response.data
}, error => {
    return Promise.reject(error)
})

// 暴露
export default axios